﻿function ChatRoomHodePageLoad() {
    var tabs = document.querySelectorAll(".tab");
}

// window.attachEvent("onload", "ChatRoomHodePageLoad");
slCtl = null;
function pluginLoaded(sender, args) {
    slCtl = sender.getHost();
    document.getElementById('SilverlightHost').style.dispaly = 'none';
    var startMeeting = document.getElementById("StartMeeting");
    if (startMeeting) {
        startMeeting.onclick = function () {
            var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=no,width=564,height=175";
            var x = screen.width / 2 - 564 / 2; var y = screen.height / 2 - 175 / 2;
            strWindowFeatures += ",left=" + x + ",top=" + y;
            var loadLyncMeetingWindow = window.open(GetCurrentWebUrl() + "/pages/Documents.aspx", "LoadingLyncMeeeting_WindowName", strWindowFeatures);
            loadLyncMeetingWindow.document.title = "正在准备Lync在线会议.......";
        };
    }

    var joinMeeting = document.getElementById("JoinMeeting");
    if (joinMeeting) {
        joinMeeting.onclick = function () { slCtl.Content.SL2JS.JoinMeeting(currentRoomInfo.meetingRoomUrl, currentRoomInfo.chatRoomId + "#" + globalConfig.meetingRoomURLPrefix); };
    }

    if (window.currentRoomInfo) {
        slCtl.Content.SL2JS.SetLyncUsers(currentRoomInfo.sIP);
        slCtl.Content.SL2JS.SetMeetingUrl(currentRoomInfo.meetingRoomUrl);
        slCtl.Content.SL2JS.SetMeetingId(currentRoomInfo.chatRoomId);
        slCtl.Content.SL2JS.SetWebUrl(GetSiteUrl());
    }

    if (loadDataComplete) {
        RenderData();
    }
   }

function onSilverlightError(sender, args) {
    // alert('test');
    document.getElementById('SilverlightHost').style.dispaly = 'none';
    console.log("Silverlight error:" + args);
}

function CallSilverlight() {
    // slCtl.Content.SL2JS.ShowAlertPopup("Testing for Calling Silverlight Method\n From Javascript");
    var currentSIP = slCtl.Content.SL2JS.GetCurrentSIP();
    alert(currentSIP);
    var avaiable = slCtl.Content.SL2JS.GetContactStatus(currentSIP);
    alert(avaiable);
} 

function ClickTab(target) {
    if (!target.classList.contains("SelectedTab")) {
        var selectedTab = document.querySelector(".SelectedTab");
        if (selectedTab) {
            selectedTab.classList.remove("SelectedTab");
            var selectContentId = selectedTab.getAttribute("contentId").valueOf();
            var selectContent = document.getElementById(selectContentId);
            selectContent.classList.add("hidden");
        }
        var newContentId = target.getAttribute("contentId").valueOf();
        var newContent = document.getElementById(newContentId);
        newContent.classList.remove("hidden");
        target.classList.add("SelectedTab");
    }
}

function GetStatusClass(statusCode, isSmall) {
    var statusClass = "ms-spimn-presence-statuscode-8x72x32";
    if (isSmall) {
        var statusClass = "ms-spimn-presence-statuscode-16x16x32";
    }  
 
    switch (statusCode) {
        case "-1":
            statusClass = statusClass.replace("statuscode", "offline");
            break;
        case "0":
            statusClass = statusClass.replace("statuscode", "offline");
            break;
        case "3500":
            statusClass = statusClass.replace("statuscode", "online");
            break;
        case "5000":
            statusClass = statusClass.replace("statuscode", "online");
            break;
        case "6500":
            statusClass = statusClass.replace("statuscode", "busy");
            break;
        case "7500":
            statusClass = statusClass.replace("statuscode", "busy");
            break;
        case "9500":
            statusClass = statusClass.replace("statuscode", "donotdisturb");
            break;
        case "12500":
            statusClass = statusClass.replace("statuscode", "away");
            break;
        case "15500":
            statusClass = statusClass.replace("statuscode", "away");
            break;
        case "18500":
            statusClass = statusClass.replace("statuscode", "offline");
            break;       
    }

    return statusClass;
}

// Update the lync user's status
function UpdateLyncUserStatus(sip, previousCode,statusCode) 
{
    var memberDiv = document.getElementById("m_" + sip);
    if (memberDiv) {
        var image = memberDiv.querySelector(".adminIndicatorImage");
        var previousClassName = GetStatusClass(previousCode, true);
        var currentClassName = GetStatusClass(statusCode, true);
        image.classList.remove(previousClassName);
        image.classList.add(currentClassName);
    }

    var adminDiv = document.getElementById("a_" + sip);
    if (adminDiv) {
        var adminImage = adminDiv.querySelector(".adminIndicatorImage");
        var previousClassName = GetStatusClass(previousCode, true);
        var currentClassName = GetStatusClass(statusCode, true);
        adminImage.classList.remove(previousClassName);
        adminImage.classList.add(currentClassName);
    }

   // UpdateMemberAvaiableLable();
}

window.UpdateLyncUserStatus = UpdateLyncUserStatus;

/*
Invalid = -1, disconnected
//
// 摘要:
//     A flag indicating that the contact state is unspecified. An application must
//     not set this flag.
None = 0, disconnected
//
// 摘要:
//     A flag indicating that the contact is available.
Free = 3500, online
//
// 摘要:
//     idle states are machine state and can not be published as user state.
FreeIdle = 5000,online
//
// 摘要:
//     A flag indicating that the contact is busy and inactive.
Busy = 6500, busy
//
// 摘要:
//     idle states are machine state and can not be published as user state.
BusyIdle = 7500,busy
//
// 摘要:
//     A flag indicating that the contact does not want to be disturbed.
DoNotDisturb = 9500,donotdisturb
//
// 摘要:
//     A flag indicating that the contact is temporarily un-alertable.
TemporarilyAway = 12500,away
//
// 摘要:
//     A flag indicating that the contact cannot be alerted.
Away = 15500, away
//
// 摘要:
//     A flag indicating that the contact is not available.
Offline = 18500, offline
*/

var globalConfig ={};
globalConfig.recordListName = "会议记录";
globalConfig.shareDocumentsName = "文档";
globalConfig.recordListId = "";
globalConfig.shareDocumentsId = "";
globalConfig.recordUpLoadUrl = "";
globalConfig.documentUpLoadUrl = "";
globalConfig.currentWebUrl = GetCurrentWebUrl();
globalConfig.meetRecordFolder = globalConfig.currentWebUrl + "/Lists/MeetingRecords/";
globalConfig.editRecordUrl = globalConfig.meetRecordFolder + "/EditForm.aspx?ID=RowId";
globalConfig.currentDocumentFolder = "root";
globalConfig.isAdmin = false;
globalConfig.currentUserId = -1;

// http://sharepoint2010/SDQ1E31Q/_layouts/hzWeb/GetLibraryTree.ashx?ListName=Documents
globalConfig.LibraryTreeJosnUrl = globalConfig.currentWebUrl + "/_layouts/hzWeb/GetLibraryTree.ashx?ListName=" + escape("文档");
var meetingRecordList;
var shareDocumentList;
ExecuteOrDelayUntilScriptLoaded(InitGlobalConfig, "sp.js");

function InitGlobalConfig() {    
    var currentcontext = new SP.ClientContext.get_current();
    meetingRecordList = currentcontext.get_web().get_lists().getByTitle(globalConfig.recordListName);
    shareDocumentList = currentcontext.get_web().get_lists().getByTitle(globalConfig.shareDocumentsName);

    currentcontext.load(meetingRecordList, 'Title', 'Id');
    currentcontext.load(shareDocumentList, 'Title', 'Id');
    currentcontext.executeQueryAsync(Function.createDelegate(this, InitGlobalConfigQuerySuccessed), Function.createDelegate(this, InitGlobalConfigQueryFailed));
}

function InitGlobalConfigQuerySuccessed() {
    globalConfig.recordListId = meetingRecordList.get_id().toString().toUpperCase();
    globalConfig.shareDocumentsId = shareDocumentList.get_id().toString().toUpperCase();

    // http://sharepoint2010/7NWEN9ZV/_layouts/Upload.aspx?List=
    globalConfig.recordUpLoadUrl = globalConfig.currentWebUrl + "/_layouts/Upload.aspx?List={" + globalConfig.recordListId + "}&RootFolder=&Source=" + document.location.href;
    var publishMeetingRecord = document.getElementById("PublishMeetingRecord");
    publishMeetingRecord.onclick = PublishMeetingRecord;

    var manageFolderStructure = document.getElementById("ManageFolderStructure");
    manageFolderStructure.onclick = ManageFolderStructure;
    globalConfig.documentUpLoadUrl = globalConfig.currentWebUrl + "/_layouts/Upload.aspx?List={" + globalConfig.shareDocumentsId + "}&RootFolder=&Source=" + document.location.href;
}

function ManageFolderStructure() {
    window.open(globalConfig.currentWebUrl + "/Documents/Forms/AllItems.aspx", null, null, null);
}

function InitGlobalConfigQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

function GetCurrentWebUrl() {
    var endUrl = "/pages/default.aspx";
    var index = document.location.href.indexOf("/pages/default.aspx");
    var currentWebUrl = document.location.href.substr(0, index);
    return currentWebUrl;
}


function openDialogForMeetingRecord(url, title) {
    var options = {
        url: url,
        width: 600,
        height: 500,
        title: title,
        dialogReturnValueCallback: CallBackfromDialog};
    SP.UI.ModalDialog.showModalDialog(options);  
    }

    function PublishMeetingRecord()
    {
        openDialogForMeetingRecord(globalConfig.recordUpLoadUrl, "上传会议记录(允许文件类型：wmv;wma;avi;mpg;mp3;mp4)");
    }

    function CallBackfromDialog(dialogResult) {
        if (dialogResult == 1) {
            // TBD：refresh the data
            RefreshMeetingRecordsData(); // defined in MeetingRecords.js
        }
        else {
            // Do nothing
        }
    }

    // Call  http://sharepoint2010/SDQ1E31Q/_layouts/hzWeb/GetConferenceMeeetingStatus.ashx?meetingId=IM05AG9T to get the meeting status
    function UpdateMeetingStatus()
    {
        if (window.currentRoomInfo) {
            var urlGetConferenceMeeetingStatus = globalConfig.currentWebUrl + "/_layouts/hzWeb/GetConferenceMeeetingStatus.ashx?meetingId=" + currentRoomInfo.chatRoomId + "&timestamp=" + (new Date()).getTime();
            $.ajax({
                type: "GET",
                url: urlGetConferenceMeeetingStatus,
                dataType: "json",
                success: function (data) {
                    var startMeeting = document.getElementById("StartMeeting");
                    var joinMeeting = document.getElementById("JoinMeeting");
                    var statusCode = null;
                    globalConfig.meetingRoomURLPrefix = data.meetingRoomURLPrefix;
                    var joinMeeting = document.getElementById("JoinMeeting");
                    if (joinMeeting && currentRoomInfo) {
                        joinMeeting.onclick = function () { slCtl.Content.SL2JS.JoinMeeting(currentRoomInfo.meetingRoomUrl, currentRoomInfo.chatRoomId + "#" + globalConfig.meetingRoomURLPrefix); };
                    }
                    if (data.isActived == true) {
                        startMeeting.classList.add("hidden");
                        joinMeeting.classList.remove("hidden");
                        statusCode = "7500";
                        //   var startMeeting = document.getElementById("StartMeeting"); 
                        // startMeeting.classList.remove("hidden");

                    }
                    else {
                        joinMeeting.classList.add("hidden");
                        startMeeting.classList.remove("hidden");
                        statusCode = "3500";
                    }

                    var className = GetStatusClass(statusCode, true);
                    var busyClass = GetStatusClass("7500", true);
                    var freeClass = GetStatusClass("3500", true);
                    var meetingStatus = document.getElementById("MeetingStatus");
                    meetingStatus.classList.remove("hidden");
                    var meetingStatusImage = document.querySelector(".MeetingStatusImage");
                    if (meetingStatusImage) {
                        meetingStatusImage.classList.remove(busyClass);
                        meetingStatusImage.classList.remove(freeClass); //hidden
                        meetingStatusImage.classList.remove("hidden");
                        meetingStatusImage.classList.add(className);
                    }
                }

            });
        }

        setTimeout(UpdateMeetingStatus, 30 * 1000);
    }

    setTimeout(UpdateMeetingStatus, 3000);